package org.restlesscode.javersion.transcoders.basic;

import org.restlesscode.javersion.SvnObject;
import org.restlesscode.javersion.SvnPropertyObject;
import org.restlesscode.javersion.Transcoder;

import java.io.*;

/**
 * A basic transcoder for a Java object. If it's given a String, write
 * the String to the content field. If it's any other object, write the
 * object using an ObjectOutputStream.
 */
public class DefaultTranscoder implements Transcoder {

    public static final String VERSION = "1.0";
    public static final String NAME = "org.restlesscode.javersion.transcoders.basic.DefaultTranscoder";


    public Object decode(SvnObject svnObject) throws IOException {
        if (svnObject.getProperty("jvn.type").getValueAsString().equals("String")) {
            return new String(svnObject.getContent());
        } else {
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(svnObject.getContent()));
            try {
                return ois.readObject();
            } catch (ClassNotFoundException e) {
                throw new IOException(e);
            }
        }
    }

    public SvnObject encode(Object o) throws IOException {
        SvnObject svnObj = new SvnObject(VERSION, NAME);

        if (o instanceof String) {
            svnObj.setProperty("jvn.type", new SvnPropertyObject("String", SvnPropertyObject.PropertyType.STRING));
            svnObj.setContent(((String) o).getBytes());
        } else {
            svnObj.setProperty("jvn.type", new SvnPropertyObject("Object", SvnPropertyObject.PropertyType.STRING));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(o);
            oos.flush();
            svnObj.setContent(baos.toByteArray());
        }

        return svnObj;
    }
}
